export class NodeUtils {

    // 查找某个子节点
    public static findChild(parent: cc.Node, childPath: string): cc.Node {
        const arr: string[] = childPath.split("/");
        let curChild: cc.Node = null;
        let curParent: cc.Node = parent;
        for (const childName of arr) {
            curChild = curParent.getChildByName(childName);
            if (!curChild) {
                return undefined;
            }
            curParent = curChild;
        }
        return curChild;

    }
    // 获取某个子节点的组件
    public static findComponent<T extends cc.Component>(node: cc.Node, nodePath: string, type: { prototype: T }): T {
        return this.findChild(node, nodePath).getComponent(type);
    }

    // 遍历某个节点
    public static walkNodeChildren(root: cc.Node, eachCallBack: (child: cc.Node) => void): void {

        for (const key in root.children) {
            const childNode: cc.Node = root.children[key];
            eachCallBack(childNode);
            if (childNode.childrenCount > 0) {
                this.walkNodeChildren(childNode, eachCallBack);
            }
        }
    }

    // 获取某个节点的世界坐标
    public static getNodeWorldRect(node: cc.Node): cc.Rect {
        const worldPos: cc.Vec2 = node.parent.convertToWorldSpaceAR(node.position);
        return cc.rect(worldPos.x, worldPos.y, node.width, node.height);
    }
}